package org.micode.libs.dao.base;

import lombok.extern.slf4j.Slf4j;
import org.micode.common.domain.base.BaseEntity;
import org.micode.common.domain.base.BaseQuery;

import java.util.ArrayList;
import java.util.List;

/**
 * 服务类,基本方法
 */
@Slf4j
public abstract class BaseInsertServiceImpl
        <KT, DTO extends BaseEntity<KT>, DO extends BaseEntity<KT>,
                QY extends BaseQuery<DO>, DAO extends BaseInsertDao<DTO>>
        extends BaseQueryServiceImpl<KT, DTO, DO, QY, DAO>
        implements BaseInsertService<KT, DTO, QY> {

    protected final int BATCH_SUBMIT_NUM = 1000;

    public BaseInsertServiceImpl() {
        super();
    }

    @Override
    public DTO insert(DTO dto) {
        beforeInsert(dto);
        int ret = getMyDao().insert(dto);
        if (ret > 0) {
            return dto;
        } else {
            return null;
        }
    }

    @Override
    public int insertBatch(List<DTO> list) {
        if (null == list || list.size() <= 0) {
            return 0;
        }

        for (DTO entity : list) {
            beforeInsert(entity);
        }

        List<DTO> insertList = new ArrayList<>();
        for (DTO dto : list) {
            insertList.add(dto);
            if (insertList.size() >= BATCH_SUBMIT_NUM) {
                getMyDao().insertBatch(insertList);
                insertList.clear();
            }
        }
        if (insertList.size() > 0) {
            getMyDao().insertBatch(insertList);
        }

        return list.size();
    }

    protected void beforeInsert(DTO entity) {
        // DTO nothing, the subclass can extends it for special process.
    }

}
